package com.librarysys.filter;

import com.librarysys.common.Const;
import com.librarysys.entity.Manager;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by yuhui on 2017/7/11.
 */
@Component
@WebFilter(filterName = "UserFilter",urlPatterns = "/*")
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        String servletPath = servletRequest1.getServletPath();
        if(!servletPath.contains("login") && !servletPath.contains("check")){
            Manager attribute = (Manager) servletRequest1.getSession().getAttribute(Const.CURRENT_USER);
            if(attribute==null){
                HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
                servletResponse1.sendRedirect("/send/login");
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
